<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="6">
        <div class="treeCol r10">
          <Selector
            v-if="props.type == 2"
            @getItem="filterPlace"
            category="学校区域"
            placeholder="请选择区域过滤"
            :style="'width:100%'"
          />
          <el-tree
            class="r10"
            :data="classOptions"
            :props="{ label: 'Name', children: 'children', isLeaf: 'isLeaf' }"
            :expand-on-click-node="false"
            ref="treeRef"
            node-key="ID"
            highlight-current
            :load="loadNode"
            lazy
            @node-click="handleNodeClick"
          ></el-tree>
        </div>
      </el-col>
      <el-col :span="18">
        <el-calendar
          v-model="DateDayFormat"
          ref="calendar"
          v-if="showCalendar"
          class="r10"
        >
          <template #header="{ date }">
            <span>{{
              classItem.Name
                ? classItem.Name
                : '请在左侧选择' + Types[props.type]
            }}</span>
            <span>{{ date }}</span>
            <el-button-group>
              <el-button size="small" @click="selectDate('prev-month')">
                上个月
              </el-button>
              <el-button size="small" @click="selectDate('today')"
                >今天</el-button
              >
              <el-button size="small" @click="selectDate('next-month')">
                下个月
              </el-button>
            </el-button-group>
          </template>
          <template v-slot:dateCell="{ data }">
            <el-popover trigger="click" placement="top" :width="200">
              <div class="flex jaround">
                <el-button @click.stop="handleClassTypeClick(1)"
                  >排课
                  <span v-show="classCount.course">
                    ({{ classCount.course }})</span
                  >
                </el-button>
                <el-button @click.stop="handleClassTypeClick(2)"
                  >考试
                  <span v-show="classCount.exame"
                    >({{ classCount.exame }})</span
                  ></el-button
                >
              </div>
              <template #reference>
                <div class="h100" @click.stop="handleClickDate(data.day)">
                  <div class="activeBar" v-if="data.day == NowDateDay"></div>
                  <div class="flex acenter jcenter h100">
                    <div class="tcenter width100" style="padding: 0 10px">
                      <div>{{ filterDate(data.day) }}</div>
                      <div
                        class="cbtn"
                        v-for="(item, index) in filterDateItem(data.day)"
                        :key="index"
                      >
                        {{ item.Name }}
                      </div>
                    </div>
                  </div>
                </div>
                <!-- <div class="dateBox" @click.stop="handleClickDate(data.day)">
                  <div>{{ filterDate(data.day) }}</div>
                  <div v-if="filterDateItem(data.day) > 0" class="tcenter">
                    <span class="courseCount">
                      {{ filterDateItem(data.day) }}</span
                    >
                    <span class="courseCountText">节</span>
                  </div>
                </div> -->
              </template>
            </el-popover>
          </template>
        </el-calendar>
        <div
          v-else
          class="flex jcenter acneter"
          style="height: 300px; line-height: 300px"
        >
          <div>{{ '请在左侧选择' + Types[props.type] }}</div>
        </div>
      </el-col>
    </el-row>
    <MyDialog
      v-model:show="show"
      :title="title"
      :destroy="true"
      :showFooter="false"
    >
      <el-row>
        <el-form inline="">
          <el-form-item label="课时方案" v-if="showSelectCoursePlan">
            <Selector category="课时方案" @getItem="getItem"></Selector>
          </el-form-item>
          <el-form-item :label="Types[props.type]">
            {{ classItem.Name }}
          </el-form-item>
          <el-form-item label="时间">{{ DateDay }} </el-form-item>
        </el-form>
      </el-row>
      <el-table
        :data="detailList"
        style="width: 100%"
        class="editTable"
        row-class-name="TableRowClass"
        header-row-class-name="TableHeaderClass"
      >
        <el-table-column align="center" prop="StartAndEnd" label="启止时间" />
        <el-table-column
          align="center"
          prop="Name_Class"
          label="班级"
          v-if="props.type != 1"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="Name_Place"
          label="场地"
          v-if="props.type != 2"
        >
        </el-table-column>

        <el-table-column
          align="center"
          prop="Name_Course"
          :label="formLabel.course"
          v-if="props.type != 3"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="Name_Teacher"
          :label="formLabel.teacher"
          v-if="props.type != 4"
        />
        <el-table-column
          align="center"
          prop="Name_Device"
          :label="formLabel.device"
          v-if="props.type != 5"
        />
        <el-table-column
          align="center"
          prop="CourseHour"
          label="课时"
          v-if="courserType == 1"
        />
        <el-table-column
          align="center"
          prop="Name_Certificate"
          label="关联证书"
          v-if="courserType == 2"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="CourseHour"
          label="操作"
          fixed="right"
          width="180px"
          v-if="showEditCol"
        >
          <template v-slot="{ row, $index }">
            <div class="flex acenter jcenter">
              <el-tooltip
                effect="light"
                content="向下插入"
                placement="top-start"
              >
                <el-icon
                  v-hasPermi="props.hasPermi.edit"
                  @click="inserRow('bottom', row, $index)"
                  class="pointer"
                  color="#409EFF"
                  :size="20"
                  ><BottomLeft
                /></el-icon>
              </el-tooltip>
              <el-tooltip
                effect="light"
                content="向上插入"
                placement="top-start"
              >
                <el-icon
                  v-hasPermi="props.hasPermi.edit"
                  @click="inserRow('top', row, $index)"
                  class="pointer mgl10 mgr10"
                  color="#409EFF"
                  :size="20"
                  ><TopLeft
                /></el-icon>
              </el-tooltip>

              <el-button
                type="text"
                v-hasPermi="props.hasPermi.edit"
                @click="editCourse(row, $index)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确认删除吗?"
                @confirm="handleDelete(row, $index)"
              >
                <template #reference>
                  <el-button
                    v-hasPermi="props.hasPermi.delete"
                    type="text"
                    style="color: red"
                    >删除</el-button
                  >
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          暂无数据
          <br />
          <el-button
            v-if="showEmptyAdd"
            type="default"
            @click="detailList = [{}]"
            >点击添加</el-button
          >
        </template>
      </el-table>
    </MyDialog>
    <MyDialog
      v-model:show="showEdit"
      :title="title"
      @confirm="confirmEdit"
      :destroy="true"
      width="1000px"
      :formRef="formRef"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        label-width="90px"
        ref="formRef"
        class="wid100"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="StartTime">
              <el-time-select
                v-model="formData.StartTime"
                :max-time="formData.EndTime"
                placeholder="请选择"
                clearable
                step="00:05"
                :start="disableStartTime"
                :end="disableEndTime"
                @change="conflictCheck()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="EndTime">
              <el-time-select
                v-model="formData.EndTime"
                :min-time="formData.StartTime"
                placeholder="请选择"
                step="00:05"
                clearable
                :end="disableEndTime"
                @change="conflictCheck()"
                :start="disableStartTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.type != 2">
            <el-form-item label="区域">
              <Selector
                v-model="formData.Area"
                @getItem="formData.ID_Place = ''"
                category="学校区域"
                :disabled="hasStartAndEnd()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.type != 2">
            <el-form-item label="场地" prop="ID_Place">
              <Selector
                v-model="formData.ID_Place"
                :query="{ ID_Area: formData.Area }"
                category="全部场地"
                :disabled="hasStartAndEnd()"
                @getItem="conflictCheck()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.type != 1">
            <el-form-item label="班级" prop="ID_Class">
              <Selector
                category="班级级联"
                cascader="级联"
                v-model="formData.ID_Class"
                v-model:placeholder="formData.ID_ClassName"
                @getItem="getClassItem()"
                :disabled="hasStartAndEnd()"
                type="string"
              ></Selector>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.type != 3">
            <el-form-item :label="formLabel.course" prop="ID_Course">
              <el-select
                clearable
                placeholder="请选择"
                v-model="formData.ID_Course"
                filterable
                @change="ChangeCourse"
                :disabled="hasStartAndEnd()"
              >
                <el-option
                  v-for="item in bindClassCourse"
                  :label="item.Name_Course"
                  :value="item.ID_Course"
                ></el-option>
              </el-select>
              <!-- <el-input
            @click="showCourse = true"
            v-model="formData.ID_CourseName"
            readonly
            placeholder="请选择"
          ></el-input> -->
            </el-form-item>
          </el-col>

          <el-col :span="8" v-if="props.type != 4">
            <el-form-item :label="formLabel.teacher" prop="ID_Teacher">
              <div class="flex acenter" style="width: 100%">
                <Selector
                  v-if="showAllTeacher"
                  category="用户列表"
                  v-model="formData.ID_Teacher"
                  :query="{
                    Type: 2
                  }"
                  :disabled="hasStartAndEnd()"
                  @getItem="conflictCheck()"
                ></Selector>
                <el-select
                  v-if="!showAllTeacher"
                  clearable
                  placeholder="请选择"
                  v-model="formData.ID_Teacher"
                  filterable
                  :disabled="hasStartAndEnd()"
                  @change="conflictCheck()"
                >
                  <el-option
                    v-for="item in bindTeachter"
                    :label="item.Name"
                    :value="item.ID"
                  ></el-option>
                </el-select>
                <el-checkbox
                  style="height: 32px"
                  class="mgl20"
                  v-model="showAllTeacher"
                  true-label="true"
                  false-label=""
                  label="全部教师"
                  size="large"
                  :disabled="hasStartAndEnd()"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="props.type != 5">
            <el-form-item :label="formLabel.device" prop="ID_Devices">
              <Selector
                category="全部设备"
                :disabled="hasStartAndEnd()"
                v-model="formData.ID_Devices"
                @getItem="conflictCheck($event)"
                :multiple="true"
                :query="{
                  Category: 1
                }"
                type="array"
              ></Selector>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="courserType == 1">
            <el-form-item label="课时" prop="CourseHour">
              <el-input
                placeholder="请输入"
                v-model="formData.CourseHour"
                :disabled="hasStartAndEnd()"
                clearable
                v-number="{ args: 'point', dotCount: 2, topNoZero: true }"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="courserType == 1">
            <el-form-item
              label="最后一堂课"
              prop="IsFinally"
              label-width="100px"
            >
              <el-radio-group
                v-model="formData.IsFinally"
                :disabled="hasStartAndEnd()"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="courserType == 2">
            <el-form-item label="关联证书" prop="ID_Certificate">
              <Selector
                category="全部证书"
                :disabled="hasStartAndEnd()"
                v-model="formData.ID_Certificate"
              ></Selector>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <div style="font-size: 18px; color: #303133" class="mgb10 mgt10">
            排课冲突
          </div>
          <MyTable
            :toolbar="false"
            :tableList="conflictList"
            :columns="columns"
            :tabTop="false"
          ></MyTable>
        </el-row>
      </el-form>
    </MyDialog>

    <MyDialog
      v-model:show="showPlace"
      title="检查冲突"
      width="800px"
      @confirm="confirmPlace"
      :destroy="true"
    >
      <AreaPlace v-model="placeData"></AreaPlace>
    </MyDialog>
    <!-- <MyDialog
      v-model:show="showCourse"
      title="类型课程"
      width="500px"
      @confirm="confirmCourse"
      :destroy="true"
    >
      <CourseAndType v-model="courseData"></CourseAndType>
    </MyDialog> -->
  </div>
</template>

<script setup name="ClassSchedule">
import { GetClassList_PID } from '@/api/school/class.js';
import AreaPlace from '@/views/schedule/ClassSchedule/AreaPlace';
import CourseAndType from '@/views/schedule/ClassSchedule/CourseAndType';

import {
  GetAlreadyScheduleDate,
  AddOrEditSchedule,
  DelSchedule,
  GetScheduleDateDetail,
  GetScheduleConflict,
  GetScheduleIDDetail
} from '@/api/schedule/class.js';
import { GetSchoolTimeDetail } from '@/api/school/classHour.js';
import { GetCourseDetail } from '@/api/lesson/lessonSystem.js';
import { getCurrentInstance } from 'vue';
import { GetClassBindCourseList } from '@/api/school/class.js';
import useUserStore from '@/store/modules/user.js';

import { GetPlaceList_Page } from '@/api/site/index.js';
const props = defineProps({
  type: {
    default: 1
  },
  hasPermi: {
    default: {
      edit: ['ClassSchedule:edit'],
      delete: ['ClassSchedule:delete']
    }
  }
});
const { proxy } = getCurrentInstance();

const value = ref();
const classOptions = ref([]);
const calendar = ref();
const classItem = ref({});
let dateList = [];
const tableList = ref([]);
const look = ref(true);
const showCalendar = ref(false);
const show = ref(false);
const showPlace = ref(false);
const title = ref('');
const detailList = ref([]);
const formData = ref({
  IsFinally: 0
});
const showSelectCoursePlan = ref(true);
const placeData = ref({});
const showCourse = ref(false);
const courseData = ref({});
const showEdit = ref(false);
const showAllTeacher = ref(false);
const bindTeachter = ref([]);
const formRef = ref({});
const DateDay = ref({});
const DateDayFormat = ref();
const editIndex = ref(-1);
const bindClassCourse = ref([]);
const showEditCol = ref(true);
const insertType = ref('');
const disableStartTime = ref('06:00');
const disableEndTime = ref('23:55');
const conflictList = ref([]);
const courserType = ref(1);
const editInfo = ref({});
const NowDateDay = proxy.$moment(new Date()).format('YYYY-MM-DD');
const formLabel = ref({
  course: '课程',
  teacher: '教师',
  device: '教学设备'
});
const classCount = ref({
  course: 0,
  exame: 0
});
const dateObj = ref({
  start: '',
  end: ''
});

const Types = {
  1: '班级',
  2: '场地',
  3: '课程',
  4: '教师',
  5: '设备'
};
//冲突
const columns = ref([
  // { label: "序号" },
  // { label: "日期", prop: "DateDay" },
  { label: '开始时间', prop: 'StartTime' },
  { label: '结束时间', prop: 'EndTime' },
  { label: '班级', prop: 'Name_Class', color: true },
  { label: '场地', prop: 'Name_Place', color: true },
  // { label: "课程", prop: "Name_Course", color: "" },
  { label: '涉及教师', prop: 'Name_Teacher', color: true },
  { label: '关联设备', prop: 'Name_Device', color: true },
  { label: '冲突类型', prop: 'TypeName' }
]);

proxy.$formatKey(columns.value);
const rules = ref({
  ID_Place: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Course: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Teacher: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Devices: [{ required: true, message: '请选择', trigger: 'change' }],
  StartTime: [{ required: true, message: '请选择', trigger: 'change' }],
  EndTime: [{ required: true, message: '请选择', trigger: 'change' }],
  CourseHour: [{ required: true, message: '请输入', trigger: 'blur' }],
  ID_Class: [{ required: true, message: '请选择', trigger: 'change' }],
  IsFinally: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Certificate: [{ required: true, message: '请选择', trigger: 'change' }]
});

const selectDate = val => {
  look.value = false;
  calendar.value.selectDate(val);
};

const showEmptyAdd = computed({
  get: () => {
    //判断可以编辑
    showEditCol.value =
      new Date(DateDay.value).getTime() >=
      new Date(proxy.$moment(new Date()).format('YYYY-MM-DD')).getTime();
    return !detailList.value?.length && showEditCol.value;
  },
  set: val => {}
});

function filterDate(date) {
  if (dateList.length != 42) dateList.push(date);
  if (dateList.length == 42) {
    let list = dateList?.sort((a, b) => {
      return new Date(a).getTime() - new Date(b).getTime();
    });
    dateObj.value = {
      start: list[0],
      end: list[list.length - 1]
    };
    getList();
    dateList = [];
  }
  return Number(date?.slice(8));
}

async function filterPlace(val) {
  try {
    let res = await GetPlaceList_Page({ NoPage: 'true', ID_Area: val.ID });
    res.data?.forEach(item => (item.isLeaf = true));
    classOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
}

function getClassItem() {
  if (!formData.value?.ID_Class) return;
  formData.value.ID_Course = '';
  formData.value.ID_Teacher = '';
  formData.value.ID_Devices = [];
  formData.value.Devices = [];
  conflictCheck();
  getCourseList(formData.value?.ID_Class);
}

function inserRow(type, row, index) {
  editIndex.value = index;
  let StartTime = row.StartAndEnd?.split('--')[0];
  let EndTime = row.StartAndEnd?.split('--')[1];
  formData.value = {
    IsFinally: 0
  };
  editInfo.value = {};
  switch (type) {
    case 'top':
      insertType.value = 'top';
      if (detailList.value[index - 1]) {
        let obj = detailList.value[index - 1];
        let preEndTime = obj.StartAndEnd?.split('--')[1];
        disableStartTime.value = preEndTime;
      } else {
        disableStartTime.value = '06:00';
      }
      disableEndTime.value = StartTime;
      break;
    case 'bottom':
      insertType.value = 'bottom';
      if (detailList.value[index + 1]) {
        let obj = detailList.value[index + 1];
        let nextStartTime = obj.StartAndEnd?.split('--')[0];
        disableEndTime.value = nextStartTime;
      } else {
        disableEndTime.value = '23:55';
      }
      disableStartTime.value = EndTime;
      break;
  }
  switch (Number(props.type)) {
    case 1:
      formData.value.ID_Class = classItem.value.ID;
      break;
    case 2:
      formData.value.ID_Place = classItem.value.ID;
      break;
  }
  switch (Number(courserType.value)) {
    case 1:
      title.value = '编辑上课信息';
      break;
    case 2:
      title.value = '编辑考试信息';
      break;
  }
  conflictList.value = [];
  showEdit.value = true;
  // formRef.value.resetField();
}
const ConflictTypes = ref({
  // "班级": 1,
  // "场地": 2,
  // "课程": 3,
  // "教师": 4,
  // "设备": 5,
});
async function conflictCheck(val) {
  let list = [];
  if (val?.all) {
    formData.value.Devices = val.all?.map(item => {
      return {
        ID_Device: item.value,
        Code: item.label,
        Name: item.code
      };
    });
  }
  if (!formData.value.StartTime || !formData.value.EndTime) return;
  if (!formData.value.ID_Devices?.length) {
    formData.value.Devices = [];
  }
  try {
    let query = {
      // ID,
      // Type,
      Date: DateDay.value,
      StartTime: DateDay.value + ' ' + formData.value.StartTime,
      EndTime: DateDay.value + ' ' + formData.value.EndTime,
      ID_Self: editInfo.value.ID
    };
    if (formData.value.ID_Class) {
      query.ID = formData.value.ID_Class;
      query.Type = 1;
      let res = await GetScheduleConflict(query);
      res.data?.forEach(item => {
        item['Name_Classcolor'] = 'red';
      });
      list = [...list, ...res.data];
    } else {
      conflictList.value = conflictList.value?.filter(
        item => !item['Name_Classcolor']
      );
    }
    if (formData.value.ID_Place) {
      query.ID = formData.value.ID_Place;
      query.Type = 2;
      let res = await GetScheduleConflict(query);
      res.data?.forEach(item => {
        item['Name_Placecolor'] = 'red';
      });
      list = [...list, ...res.data];
    } else {
      conflictList.value = conflictList.value?.filter(
        item => !item['Name_Placecolor']
      );
    }
    if (formData.value.ID_Teacher) {
      query.ID = formData.value.ID_Teacher;
      query.Type = 4;
      let res = await GetScheduleConflict(query);
      res.data?.forEach(item => {
        item['Name_Teachercolor'] = 'red';
      });
      list = [...list, ...res.data];
    } else {
      conflictList.value = conflictList.value?.filter(
        item => !item['Name_Teachercolor']
      );
    }
    if (formData.value.Devices?.length) {
      let result = await Promise.all(
        formData.value.Devices?.map(async item => {
          query.ID = item.ID_Device;
          query.Type = 5;
          let { data } = await GetScheduleConflict(query);
          data?.forEach(item => {
            item['Name_Devicecolor'] = 'red';
          });
          return data;
        })
      );
      result?.map(item => {
        list = [...list, ...item];
      });
    } else {
      conflictList.value = conflictList.value?.filter(
        item => !item['Name_Devicecolor']
      );
    }
    list?.forEach(item => {
      item.StartTime = item.StartTime?.slice(11, 16);
      item.EndTime = item.EndTime?.slice(11, 16);
      item.TypeName = item.Type == 1 ? '上课冲突' : '考试冲突';
    });

    conflictList.value = list;
  } catch (error) {
    console.log(error);
  }
}

async function ChangeCourse(val) {
  if (!val) {
    formData.value.ID_Teacher = '';
    formData.value.ID_Devices = [];
    formData.value.Devices = [];
    return;
  }
  let courseOobj = bindClassCourse.value?.find(
    item => item?.ID_Course == formData.value.ID_Course
  );
  formData.value.ID_Teacher = courseOobj?.ID_Teacher;

  try {
    let res = await GetCourseDetail({ ID: courseOobj?.ID_Course });
    formData.value.ID_Devices = res.data?.BindDevices?.map(
      item => item.ID_Device
    );
    formData.value.Devices = res.data?.BindDevices?.map(item => {
      return {
        ID_Device: item.ID_Device,
        Code: item.Code,
        Name: item.Name
      };
    });
    conflictList.value = [];
    if (formData.value.Devices?.length) {
      let list = formData.value.Devices?.map(item => {
        return {
          value: item.ID_Device,
          code: item.Code,
          name: item.Name
        };
      });

      conflictCheck({ all: list });
    }
  } catch (error) {
    console.log(error);
  }
}

function confirmPlace() {
  if (!placeData.value.isLeaf) {
    return proxy.$modal.msgError('请选择区域下的场地');
  }
  formData.value.ID_Place = placeData.value.ID;
  // addOrEdit();
}

function handleNodeClick(val) {
  switch (Number(props.type)) {
    case 1:
      if (val.Type != 4) return;
      break;
    case 2:
      break;
    case 3:
      if (val.Type != 4) return;
      break;
    case 4:
      if (val.Type != 4) return;
      break;
    case 5:
      if (val.Type != 4) return;
      break;
  }
  showCalendar.value = true;
  look.value = false;
  classItem.value = val;
}

async function getList() {
  if (!classItem.value.ID) return;
  if (look.value) return;
  look.value = true;
  try {
    let query = {
      ID: classItem.value.ID,
      Type: props.type,
      StartTime: dateObj.value.start,
      EndTime: dateObj.value.end
    };

    let res = await GetAlreadyScheduleDate(query);
    res.data?.forEach(item => {
      item.Date = item.Date?.slice(0, 10);
    });
    tableList.value = res.data;
    look.value = true;
  } catch (error) {
    console.log(error);
  }
}

function hasStartAndEnd() {
  let bool = true;
  switch (Number(props.type)) {
    case 1:
      bool = !formData.value.StartTime || !formData.value.EndTime;
      break;
    case 2:
      bool = !formData.value.StartTime || !formData.value.EndTime;
      break;
  }
  return bool;
}

async function confirmEdit(val) {
  if (val) {
    try {
      let query = {
        ...formData.value,

        DateDay: DateDay.value,
        StartTime: DateDay.value + ' ' + formData.value.StartTime,
        EndTime: DateDay.value + ' ' + formData.value.EndTime,
        Type: courserType.value
        // ID_Class: classItem.value.ID,
      };
      let { data } = await AddOrEditSchedule(query);
      if (formData.value.ID) {
        proxy.$modal.msgSuccess('修改成功');
      } else {
        proxy.$modal.msgSuccess('添加成功');
      }

      let res = await GetScheduleIDDetail({ ID: data });
      res.data.Name_Device = res.data?.Devices?.map(item => item.Name).join(
        ','
      );
      let rowData = {
        ...res.data,
        StartTime: res.data.StartTime.slice(11, 16),
        EndTime: res.data.StartTime.slice(11, 16),
        StartAndEnd:
          res.data.StartTime.slice(11, 16) +
          '--' +
          res.data.EndTime.slice(11, 16)
      };
      //是编辑还是插入
      if (insertType.value) {
        switch (insertType.value) {
          case 'top':
            detailList.value.splice(editIndex.value, 0, rowData);
            break;
          case 'bottom':
            detailList.value.splice(editIndex.value + 1, 0, rowData);
            break;
        }
      } else {
        detailList.value[editIndex.value] = rowData;
      }
      showEdit.value = false;
      courseData.value = {};
      placeData.value = {};
      showSelectCoursePlan.value = false;
      // classItem.value = {
      //   ...classItem.value,
      // };
      look.value = false;
      getList();
    } catch (error) {
      console.log(error);
    }
  }
}

async function handleDelete(row, index) {
  try {
    if (row.ID) await DelSchedule({ ID: row.ID });
    proxy.$modal.msgSuccess('删除成功');
    detailList.value.splice(index, 1);

    look.value = false;
    getList();
  } catch (error) {
    console.log(error);
  }
}

async function editCourse(row, index) {
  let res = {};
  if (row.ID) {
    res = await GetScheduleIDDetail({ ID: row.ID });
  }
  editIndex.value = index;
  disableStartTime.value = '06:00';
  disableEndTime.value = '23:55';
  formData.value = {
    ...row,
    ID: row.ID,
    StartTime: row.StartAndEnd?.split('--')[0],
    EndTime: row.StartAndEnd?.split('--')[1],
    CourseHour: row.CourseHour,
    DateDay: DateDay,
    IsFinally: row.IsFinally ? row.IsFinally : 0,
    ID_Devices: res.data?.Devices?.map(item => item.ID_Device) || [],
    Devices: res.data?.Devices?.map(item => {
      return {
        ID_Device: item.ID_Device,
        Code: item.Code,
        Name: item.Name
      };
    })
  };

  editInfo.value = {
    ...row
  };

  switch (Number(props.type)) {
    case 1:
      formData.value.ID_Class = classItem.value.ID;
      break;
    case 2:
      formData.value.ID_Place = classItem.value.ID;
      formData.value.ID_ClassName = row.Name_Class;
      break;
  }
  if (row.ID_Class) {
    getCourseList(row.ID_Class);
  }
  insertType.value = '';
  conflictList.value = [];
  conflictCheck();
  showEdit.value = true;
}

function filterDateItem(date) {
  let obj = tableList.value?.find(item => item.Date == date) || {};
  obj.AlreadyCount =
    obj.AlreadyCount?.length > 2
      ? obj.AlreadyCount.slice(0, 2)
      : obj.AlreadyCount;
  return obj.AlreadyCount;
}

async function getItem(item) {
  try {
    let res = await GetSchoolTimeDetail({ ID: item.ID });
    detailList.value = res.data?.Nodes?.map(node => {
      return {
        StartAndEnd: node.StartTime + '--' + node.EndTime,
        CourseHour: node.CourseHour
      };
    });
  } catch (error) {
    console.log(error);
  }
}

function handleClassTypeClick(Type) {
  if (!classItem.value.ID)
    return proxy.$modal.msgError('请先选择' + Types[props.type]);
  courserType.value = Type;
  switch (Type) {
    case 1:
      title.value = '编辑排课';
      formLabel.value = {
        course: '课程',
        teacher: '教师',
        device: '教学装备'
      };
      break;
    case 2:
      title.value = '编辑考试';
      formLabel.value = {
        course: '关联课程',
        teacher: '监考老师',
        device: '教学装备'
      };
      break;
  }

  detailList.value = detailList.value?.filter(item => item.Type == Type);
  show.value = true;
}

async function handleClickDate(date) {
  if (!classItem.value.ID)
    return proxy.$modal.msgError('请先选择' + Types[props.type]);
  courserType.value = '';
  //判断可以编辑
  showEditCol.value =
    new Date(date).getTime() >=
    new Date(proxy.$moment(new Date()).format('YYYY-MM-DD')).getTime();
  DateDay.value = date;
  DateDayFormat.value = new Date(date);
  formData.value = {};
  try {
    let query = {
      ID: classItem.value.ID,
      Type: props.type,
      Date: date,
      Type_Class: courserType.value
    };
    let res = await GetScheduleDateDetail(query);
    res.data?.forEach(item => {
      item.StartAndEnd =
        item.StartTime?.slice(11, 16) + '--' + item.EndTime?.slice(11, 16);
      // item.StartTime = item.StartTime.slice(11);
    });
    detailList.value = res.data;
    let course = detailList.value?.filter(item => item.Type == 1)?.length;
    let exame = detailList.value?.filter(item => item.Type == 2)?.length;
    classCount.value = {
      course,
      exame
    };
    if (detailList.value?.length || !showEditCol.value) {
      showSelectCoursePlan.value = false;
    } else {
      showSelectCoursePlan.value = true;
    }
    if (props.type == 1) {
      getCourseList(classItem.value.ID);
    }
  } catch (error) {
    console.log(error);
  }
}

async function getCourseList(ID) {
  //班级ID
  try {
    let bindCourse = await GetClassBindCourseList({ ID });
    bindClassCourse.value = bindCourse.data;
    bindTeachter.value = bindClassCourse.value?.map(item => {
      return {
        ID: item.ID_Teacher,
        Name: item.Name_Teacher
      };
    });
  } catch (error) {
    console.log(error);
  }
}

function handleCourseClick(row) {
  formData.value.ID = row.ID;
  showCourse.value = true;
}

function handlePlaceClick(row) {
  formData.value.ID = row.ID;
  showPlace.value = true;
}

async function loadNode(node, resolve) {
  try {
    let res;
    let list = [];

    switch (Number(props.type)) {
      case 1:
        if (node.level == 0) {
          res = await GetClassList_PID({ ID: 0 });
        } else {
          res = await GetClassList_PID({ ID: node.data.ID });
        }
        list = res.data?.map(item => {
          return {
            ...item.Info,
            isLeaf: !item.IsHasChild
          };
        });
        break;
      case 2:
        if (node.level == 0) {
          res = await GetPlaceList_Page({ NoPage: 'true' });
        }
        list = res.data?.map(item => {
          return {
            ...item,
            isLeaf: true
          };
        });
        break;
    }
    resolve(list);
  } catch (error) {
    console.log(error);
  }
}
</script>

<style lang="scss" scoped>
.courseType {
  &:hover {
    cursor: pointer;
    color: $color;
    box-shadow: 0 0 4px #ddd;
  }
  color: white;
  background-color: rgb(190, 190, 190);
  padding: 10px 20px;
  border: 1px solid #ddd;
  border-radius: 6px;
}
:deep(.el-calendar-table .el-calendar-day) {
  padding: 0;

  .dateBox {
    padding: 10px;
    height: 100%;
  }
}
.courseCount {
  font-weight: bool;
  display: inline-block;
  font-size: 20px;
  border-radius: 50%;
  border: 1px solid rgb(204, 202, 202);
  width: 30px;
  height: 30px;
  line-height: 30px;
}
.courseCountText {
  color: rgb(187, 185, 185);
  line-height: 30px;
  margin-left: 6px;
}
.treeCol {
  min-height: calc(100vh - 108px);
  background-color: white;
}
.cbtn {
  color: white;
  font-size: 12px;
  border-radius: 3px;
  margin-top: 4px;
  word-break: keep-all;
  text-overflow: ellipsis;
  overflow: hidden;
  &:not(.more) {
    &:nth-child(2) {
      background-color: #356df2;
    }
    &:nth-child(3) {
      background-color: #ff69b4;
    }
  }
  &.more {
    border: 1px solid #ddd;
    color: #000000;
  }
}
:deep(.el-calendar) {
  .el-calendar__body {
    .el-calendar-table {
      border-spacing: 10px;
      background-color: #f4f8ff;
      td {
        border: none !important;
        background-color: white;
        border-radius: 10px;
        overflow: hidden;
      }
    }
  }
}
.activeBar {
  background-color: #356df2;
  height: 5px;
  border-radius: 2.5px;
}
</style>
